package com.atguigu.spzx.user.controller;

import com.atguigu.spzx.common.util.AuthUtil;
import com.atguigu.spzx.model.entity.user.UserAddress;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.user.service.UserAddressService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user/userAddress")
@Tag(name = "用户地址管理模块")
public class UserAddressController {
    @Resource
    UserAddressService userAddressService;

    @Operation(summary = "获取地址信息")
    @GetMapping("/getUserAddress/{id}")
    public Result getUserAddress(@PathVariable("id")Long id){
        UserAddress userAddress = userAddressService.getById(id);
        return Result.ok().data(userAddress);
    }
    @Operation(summary = "修改地址信息")
    @PutMapping("/auth/updateById")
    public Result updateById(@RequestBody UserAddress userAddress){
        //如果修改的地址 是默认的，需要先更新当前用户的其他所有地址为非默认
        if(userAddress.getIsDefault().intValue()==1){
            userAddressService.update(Wrappers.lambdaUpdate(UserAddress.class)
                    .set(UserAddress::getIsDefault , 0)
                    .eq(UserAddress::getUserId , AuthUtil.getUserInfo().getId())
                    .eq(UserAddress::getIsDefault , 1));
        }
        userAddressService.updateById(userAddress);
        return Result.ok();
    }
    @Operation(summary = "新增地址信息")
    @PostMapping("/auth/save")
    public Result save(@RequestBody UserAddress userAddress){
        userAddressService.saveUserAddress(userAddress);
        return Result.ok();
    }
    @Operation(summary = "获取地址信息列表")
    @GetMapping("/auth/findUserAddressList")
    public Result findUserAddressList(){
        List<UserAddress> userAddresses = userAddressService.list(Wrappers.lambdaQuery(UserAddress.class)
                .eq(UserAddress::getUserId, AuthUtil.getUserInfo().getId()));
        return Result.ok().data(userAddresses);
    }
    @Operation(summary = "删除地址信息")
    @DeleteMapping("/auth/removeById/{id}")
    public Result removeById(@PathVariable("id")Long id){
        userAddressService.removeById(id);
        return Result.ok();
    }
}
